#pragma once 
#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "common.hpp"

//将填充
class InetAddr
{
private:
    void Portn2hs()
    {
        _ip=::ntohs(_net_addr.sin_addr.s_addr);
    }
    void IPn2hs()
    {
        char buff[64];
        const char *ip = ::inet_ntop(AF_INET, &_net_addr.sin_addr , buff , sizeof(buff));
        if (ip) 
        {
            _ip = ip;  // 将转换后的IP字符串存入成员变量 _ip
        } else 
        {
            _ip = "";  // 转换失败时设为空字符串
        }
    }
public:
    InetAddr()
    {}
    InetAddr(struct sockaddr_in net_addr):_net_addr(net_addr)
    {
        Portn2hs();
        IPn2hs();
    }
    InetAddr(uint16_t port):_port(port) ,_ip("")
    {
        bzero(&_net_addr, sizeof(_net_addr));//先置零
        _net_addr.sin_family = AF_INET;  
        _net_addr.sin_port = ::htons(_port); // 要被发送给对方的，即要发到网络中！
        _net_addr.sin_addr.s_addr = INADDR_ANY;//一个服务器可能对应多个IP地址
    }

    struct sockaddr *NetAddr() { return CONV(&_net_addr); }
    socklen_t NetAddrLen() { return sizeof(_net_addr); }

    std::string IP(){return _ip;}
    uint16_t Port(){return _port;}
    std::string Addr()
    {
        return IP() + ":" + std::to_string(Port());
    }
    bool operator==(const InetAddr&addr)
    {
        return addr._ip==_ip && addr._port ==_port;
    }
    ~InetAddr()
    {}
    
private:
    struct sockaddr_in _net_addr;
    std::string _ip; 
    uint16_t _port;
};